package com.icetec.iceintel.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import java.util.ArrayList;
import java.util.Comparator;

import java.util.Set;
import java.util.TreeSet;

import com.icetec.iceintel.database.AlarmConfigSqlHelper;
import com.icetec.iceintel.model.Alarm;


public class AlarmService extends Service {

	@Override
	public IBinder onBind(Intent intent) {

		return null;
	}


	@Override
	public void onCreate() {
		Log.d(this.getClass().getSimpleName(), "onCreate()");
		super.onCreate();		
	}

	private Alarm getNext(){

        //构建闹钟集，将闹钟按照时间总最近到最长排列
		Set<Alarm> alarmQueue = new TreeSet<Alarm>(new Comparator<Alarm>() {
			@Override
			public int compare(Alarm lhs, Alarm rhs) {
				int result = 0;
				long diff = lhs.getAlarmTime().getTimeInMillis() - rhs.getAlarmTime().getTimeInMillis();				
				if(diff>0){
					return 1;
				}else if (diff < 0){
					return -1;
				}
				return result;
			}
		});

        //从数据库获取闹钟集
		ArrayList<Alarm> alarms =new AlarmConfigSqlHelper().getAllAlarm();

        //激活的闹钟，入队
		for(Alarm alarm : alarms){
			if(alarm.getAlarmActive())
				alarmQueue.add(alarm);
		}
		if(alarmQueue.iterator().hasNext()){
			return alarmQueue.iterator().next();
		}else{
			return null;
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}


	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(this.getClass().getSimpleName(), "onStartCommand()");

        //获得下一个闹钟,非空则启动这个闹钟的调度
		Alarm alarm = getNext();
		if(null != alarm){
			alarm.schedule(getApplicationContext());
			Log.d(this.getClass().getSimpleName(), alarm.getTimeUntilNextAlarmMessage());
			
		}else{
        //如果无法取得下一个闹钟，则取消本次闹钟的调度

			Intent myIntent = new Intent(getApplicationContext(), AlarmAlertBroadcastReciever.class);
			myIntent.putExtra("alarm", new Alarm());
			
			PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);
			AlarmManager alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
			alarmManager.cancel(pendingIntent);
		}
		return START_NOT_STICKY;
	}

}
